<template>
  <el-dialog
    v-model="visible"
    title="批量操作"
    width="800px"
    :before-close="handleClose"
    class="batch-operation-dialog"
  >
    <div class="batch-operation-container">
      <el-tabs v-model="activeTab" class="operation-tabs">
        <!-- 智能匹配 -->
        <el-tab-pane label="智能匹配" name="match" class="tab-pane">
          <div class="operation-content">
            <el-alert
              title="智能匹配将根据交易金额、时间等信息自动匹配对应的订单数据"
              type="info"
              show-icon
              class="operation-alert"
            />
            
            <el-form :model="matchOptions" label-width="120px" class="match-options">
              <el-form-item label="匹配策略">
                <el-radio-group v-model="matchOptions.strategy">
                  <el-radio value="auto">自动匹配</el-radio>
                  <el-radio value="manual">手动确认</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="匹配准确度">
                <el-slider 
                  v-model="matchOptions.accuracy" 
                  :min="50" 
                  :max="100" 
                  show-input
                  class="accuracy-slider"
                />
              </el-form-item>
              
              <el-form-item label="处理未匹配项">
                <el-switch 
                  v-model="matchOptions.handleUnmatched"
                  active-text="自动标记为待处理"
                  class="unmatched-switch"
                />
              </el-form-item>
            </el-form>
            
            <div class="match-preview">
              <h4>匹配预览</h4>
              <el-table :data="matchPreview" style="width: 100%" class="preview-table">
                <el-table-column prop="transactionId" label="流水号" width="180" />
                <el-table-column prop="amount" label="交易金额" width="120">
                  <template #default="scope">
                    <span :class="getAmountClass(scope.row.amount)">
                      {{ formatCurrency(scope.row.amount) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="transactionDate" label="交易时间" width="180" />
                <el-table-column label="匹配状态" width="120">
                  <template #default="scope">
                    <el-tag :type="scope.row.matched ? 'success' : 'warning'">
                      {{ scope.row.matched ? '已匹配' : '未匹配' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="orderId" label="订单号" width="180" />
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 批量过滤 -->
        <el-tab-pane label="批量过滤" name="filter" class="tab-pane">
          <div class="operation-content">
            <el-alert
              title="批量过滤可以将选中的流水标记为非业务相关或其他指定原因"
              type="info"
              show-icon
              class="operation-alert"
            />
            
            <el-form :model="filterOptions" label-width="120px" class="filter-options">
              <el-form-item label="过滤原因">
                <el-radio-group v-model="filterOptions.reason">
                  <el-radio value="non-business">非业务相关</el-radio>
                  <el-radio value="internal-transfer">内部转账</el-radio>
                  <el-radio value="salary">工资收入</el-radio>
                  <el-radio value="refund">退款交易</el-radio>
                  <el-radio value="other">其他原因</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item v-if="filterOptions.reason === 'other'" label="自定义原因">
                <el-input 
                  v-model="filterOptions.customReason" 
                  placeholder="请输入过滤原因"
                  class="custom-reason-input"
                />
              </el-form-item>
              
              <el-form-item label="应用范围">
                <el-checkbox 
                  v-model="filterOptions.applyToAll" 
                  class="apply-to-all-checkbox"
                >
                  应用到所有匹配的流水
                </el-checkbox>
              </el-form-item>
            </el-form>
            
            <div class="filter-preview">
              <h4>过滤预览</h4>
              <el-table :data="filterPreview" style="width: 100%" class="preview-table">
                <el-table-column prop="transactionId" label="流水号" width="180" />
                <el-table-column prop="amount" label="交易金额" width="120">
                  <template #default="scope">
                    <span :class="getAmountClass(scope.row.amount)">
                      {{ formatCurrency(scope.row.amount) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="transactionDate" label="交易时间" width="180" />
                <el-table-column prop="payerName" label="付款方" width="150" />
                <el-table-column label="过滤原因" width="150">
                  <template #default="scope">
                    <el-tag type="warning">{{ scope.row.filterReason }}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 批量导出 -->
        <el-tab-pane label="批量导出" name="export" class="tab-pane">
          <div class="operation-content">
            <el-alert
              title="将选中的流水数据导出为Excel、CSV等格式"
              type="info"
              show-icon
              class="operation-alert"
            />
            
            <el-form :model="exportOptions" label-width="120px" class="export-options">
              <el-form-item label="导出格式">
                <el-radio-group v-model="exportOptions.format">
                  <el-radio value="excel">Excel (.xlsx)</el-radio>
                  <el-radio value="csv">CSV (.csv)</el-radio>
                  <el-radio value="pdf">PDF (.pdf)</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="导出内容">
                <el-checkbox-group v-model="exportOptions.fields">
                  <el-checkbox value="transactionId">流水号</el-checkbox>
                  <el-checkbox value="transactionDate">交易日期</el-checkbox>
                  <el-checkbox value="payerName">付款方</el-checkbox>
                  <el-checkbox value="amount">交易金额</el-checkbox>
                  <el-checkbox value="balance">账户余额</el-checkbox>
                  <el-checkbox value="remark">交易备注</el-checkbox>
                  <el-checkbox value="bankName">银行名称</el-checkbox>
                  <el-checkbox value="matchStatus">匹配状态</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="文件名">
                <el-input v-model="exportOptions.fileName" placeholder="请输入文件名">
                  <template #append>.{{ exportOptions.format }}</template>
                </el-input>
              </el-form-item>
            </el-form>
            
            <div class="export-preview">
              <h4>导出预览</h4>
              <div class="preview-info">
                <p>将导出 <strong>{{ selectedCount }}</strong> 条流水记录</p>
                <p>文件大小预计：<strong>{{ formatFileSize(estimateFileSize()) }}</strong></p>
                <p>导出耗时预计：<strong>{{ estimateExportTime() }}秒</strong></p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="executeOperation"
          :loading="operating"
        >
          执行操作
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  modelValue: boolean,
  selectedTransactions: any[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'batch-action', action: string, options: any): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const activeTab = ref('match')
const operating = ref(false)

const selectedCount = computed(() => props.selectedTransactions.length)

// 匹配选项
const matchOptions = reactive({
  strategy: 'auto',
  accuracy: 85,
  handleUnmatched: true
})

// 过滤选项
const filterOptions = reactive({
  reason: 'non-business',
  customReason: '',
  applyToAll: false
})

// 导出选项
const exportOptions = reactive({
  format: 'excel',
  fields: ['transactionId', 'transactionDate', 'payerName', 'amount', 'remark'],
  fileName: `银行流水_${new Date().toISOString().slice(0, 10)}`
})

// 预览数据
const matchPreview = computed(() => {
  return props.selectedTransactions.slice(0, 5).map(transaction => ({
    ...transaction,
    matched: Math.random() > 0.3
  }))
})

const filterPreview = computed(() => {
  const reasonMap: Record<string, string> = {
    'non-business': '非业务相关',
    'internal-transfer': '内部转账',
    'salary': '工资收入',
    'refund': '退款交易',
    'other': filterOptions.customReason || '其他'
  }
  
  return props.selectedTransactions.slice(0, 5).map(transaction => ({
    ...transaction,
    filterReason: reasonMap[filterOptions.reason]
  }))
})

const formatCurrency = (amount: number) => {
  const absAmount = Math.abs(amount)
  const sign = amount >= 0 ? '' : '-'
  return sign + '¥' + absAmount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const estimateFileSize = () => {
  // 简单估算：每条记录约1KB
  return selectedCount.value * 1024
}

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

const estimateExportTime = () => {
  // 简单估算：每100条记录约1秒
  return Math.ceil(selectedCount.value / 100)
}

const executeOperation = async () => {
  operating.value = true
  try {
    let action = ''
    let options = {}
    
    switch (activeTab.value) {
      case 'match':
        action = 'match'
        options = { ...matchOptions }
        break
      case 'filter':
        action = 'filter'
        options = { 
          ...filterOptions,
          reasonText: filterOptions.reason === 'other' ? filterOptions.customReason : ''
        }
        break
      case 'export':
        action = 'export'
        options = { ...exportOptions }
        break
    }
    
    // 模拟操作执行
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    emit('batch-action', action, options)
    ElMessage.success('批量操作执行成功')
    handleClose()
  } catch (error) {
    ElMessage.error('操作执行失败')
  } finally {
    operating.value = false
  }
}

const handleClose = () => {
  visible.value = false
}

// 监听选中项变化，更新预览
watch(() => props.selectedTransactions, () => {
  // 预览数据会自动更新
}, { deep: true })

const getAmountClass = (amount: number) => {
  if (amount > 0) {
    return 'amount-in'
  } else if (amount < 0) {
    return 'amount-out'
  }
  return ''
}
</script>

<style scoped lang="scss">
.batch-operation-container {
  min-height: 400px;
}

.operation-content {
  padding: 10px 0;
}

.match-options,
.filter-options,
.export-options {
  margin-bottom: 20px;
}

.operation-alert {
  margin-bottom: 20px;
}

.accuracy-slider {
  width: 300px;
}

.unmatched-switch {
  margin-left: 10px;
}

.custom-reason-input {
  width: 300px;
}

.apply-to-all-checkbox {
  margin-left: 10px;
}

.match-preview,
.filter-preview,
.export-preview {
  margin-top: 20px;
  
  h4 {
    margin-bottom: 15px;
    color: #606266;
  }
}

.preview-table {
  margin-bottom: 20px;
}

.preview-info {
  p {
    margin: 10px 0;
    color: #606266;
    
    strong {
      color: #303133;
    }
  }
}

.amount-in {
  color: #67c23a;
}

.amount-out {
  color: #f56c6c;
}

.dialog-footer {
  text-align: right;
}
</style>